package org.wx.io.netty.chart.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.wx.io.netty.chart.client.ChartClientHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @description: netty chart 客户端
 * @author: wangxun
 * @createDate: 2021/2/18
 * @version: 1.0
 */
@Slf4j
public class NettyChartClient {

    volatile boolean flag = true;

    public static void main(String[] args) {
        NettyChartClient client = new NettyChartClient();
        client.doConnect("127.0.0.1",9000);
    }


     void doConnect(String inetHost,int inPort){
        NioEventLoopGroup  workerGroup = new NioEventLoopGroup(1);
        try {

            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new LoggingHandler(LogLevel.TRACE));
                            pipeline.addLast(new IdleStateHandler(60,20,60*10, TimeUnit.SECONDS));
                            pipeline.addLast(new ChartClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(inetHost, inPort);
            channelFuture.addListener(new ClientListener());

            // 开启输入....
            Thread enter = new Thread(() -> {
                Scanner scanner = new Scanner(System.in);
                while (scanner.hasNextLine()) {
                    if(!flag){
                        return;
                    }

                    String msg = scanner.nextLine();
                    if (msg != null) {
                        // 退出
                        if ("exit".equals(msg)) {
                            // 关闭渠道
                            channelFuture.channel().close();
                            break;
                        }
                        // 写出数据
                        channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8));
                    }
                }
            });
            enter.start();


            ChannelFuture closeFuture = channelFuture.channel().closeFuture().sync();
            closeFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info("退出聊天室...");
                    flag = false;
                }
            });


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //workerGroup.shutdownGracefully();
        }
    }
}
